package live.zs.securitytokenstarter.config;

import live.zs.securitytokenstarter.filter.JwtAuthenticationTokenFilter;
import live.zs.securitytokenstarter.security.JwtTokenManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.BeanIds;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsUtils;

import javax.servlet.http.HttpServletResponse;


/**
 * @author madison
 * @description
 * @date 2021/7/15 20:07
 */
//加入spring-boot-starter-security依赖就会自动启用
//@EnableWebSecurity
@Slf4j
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    public static final String LOGIN_ENTRY_POINT = "/auth/login";
    public static final String SECURITY_IGNORE_URLS_SPILT_CHAR = ",";

    @Autowired
    private JwtTokenManager tokenManager;
    @Value("${security.ignore.urls}")
    private String ignoreUrls;

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().mvcMatchers(ignoreUrls.split(SECURITY_IGNORE_URLS_SPILT_CHAR));
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.headers(
                header -> header.disable()  //禁用缓存
        ).sessionManagement(
                session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)   // 基于token，所以不需要session
        ).csrf(
                csrf -> csrf.disable()   //CSRF - Cross-Site Request Forgery - 跨站请求伪造
        ).authorizeRequests(
                auth -> auth.antMatchers(LOGIN_ENTRY_POINT).permitAll()
                        .requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
                        .anyRequest().authenticated()
        ).addFilterBefore(
                new JwtAuthenticationTokenFilter(tokenManager),     // 添加JWT filter
                UsernamePasswordAuthenticationFilter.class
        ).exceptionHandling(
                handling -> handling.authenticationEntryPoint(jwtAuthenticationEntryPoint())    //添加自定义未授权和未登录结果返回
        );

    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(customUserDetailsService())
                .passwordEncoder(new BCryptPasswordEncoder());
    }

    @Bean(name = BeanIds.AUTHENTICATION_MANAGER)
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    CustomUserDetailsService customUserDetailsService() {
        return new CustomUserDetailsService();
    }

    AuthenticationEntryPoint jwtAuthenticationEntryPoint() {
        return (request, response, e) -> {
            log.error("Responding with unauthorized error. Message:{}, url:{}", e.getMessage(), request.getRequestURI());
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
        };
    }
}
